<?php
namespace App\Http\Controllers\Api\Trade\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Trade\Demand\MyListRequest;
use App\Http\Requests\Trade\Demand\ItemRequest;
use App\Http\Requests\Trade\Demand\ItemStatusRequest;
use App\Http\Requests\Trade\Demand\ItemCollectionRequest;
use App\Http\Resources\Trade\Supply\ListResource as SupplyListResource;
use App\Http\Resources\Trade\Demand\DetailResource as DemandDetailResource;
use App\Http\Resources\Trade\Demand\ListResource as DemandListResource;
use App\Http\Resources\Trade\Demand\RejectListResource;
use App\Models\Trade\Demand\DemandCountVisitModel;
use App\Services\Trade\Auth\DemandService;
use App\Exceptions\Response\Request\RequestException;
use App\Exceptions\Response\Request\RequestCode;

class DemandController extends Controller
{

    /**
     * 我的数据列表
     *
     * @param $page 可选            
     * @param $page_size 可选            
     * @param $status 可选            
     */
    public function getMyList(MyListRequest $request)
    {
        $page = intval($request->query('page', 1));
        $pageSize = intval($request->query('page_size', 50));
        $status = $request->query('status', MyListRequest::STATUS_DEFAULT);
        $userId = $this->identity()->getUserId();
        
        $demandService = new DemandService();
        list ($collection, $count) = $demandService->selectList($page, $pageSize, $status, $userId);
        
        $data['count'] = [
            'total' => $count,
            'page' => $page,
            'page_size' => $pageSize
        ];
        $data['data'] = new DemandListResource($collection);
        
        // 获取驳回原因
        if ($status == MyListRequest::STATUS_REJECT && $collection->count()) {
            $collectionReject = $demandService->selectRejectList($collection->pluck('id')->all());
            // 数据解码
            $data['data_reject'] = new RejectListResource($collectionReject);
        }
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 发布成功推荐列表
     *
     * @param $id 必选            
     * @param $page_size 可选            
     */
    public function getItemMoers(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1',
            'page_size' => 'nullable|integer|between:1,100'
        ]);
        $id = $request->query('id');
        $pageSize = $request->query('page_size', 5);
        
        // 出售列表，求购统计
        $demandService = new DemandService();
        list ($collection, $shopCount) = $demandService->selectItemMoers($id, $pageSize);
        
        $data['count'] = $shopCount;
        $data['data'] = new SupplyListResource($collection);
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 获取编辑数据
     *
     * @param $id 必选            
     */
    public function getItem(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $id = $request->query('id');
        
        $demandService = new DemandService();
        $data = $demandService->findItem($id)->shift();
        $data = DemandDetailResource::makeEditDataDecode($data);
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 保存数据（一条）
     */
    public function saveItem(ItemRequest $request)
    {
        // 参数数据
        $id = $request->input('id');
        $sizeMin = $request->input('size_min');
        $sizeMax = $request->input('size_max');
        $sizeUnitId = $request->input('size_unit_id');
        // 特殊验证
        if ($sizeUnitId < - 1 || $sizeUnitId == 0) {
            throw new RequestException(RequestCode::REQUEST_CODE, '', [
                'size_unit_id' => [
                    'size_unit_id 必须大于 0，或者等于-1'
                ]
            ]);
        }
        if ($sizeUnitId > 0 && empty($sizeMin) && empty($sizeMax)) {
            throw new RequestException(RequestCode::REQUEST_CODE, '', [
                'size_min|size_max' => [
                    '当 size_unit_id 大于 0 时，size_min|size_max 至少一个不能为空'
                ]
            ]);
        }
        // 保存数据
        $demandService = new DemandService();
        $number = $demandService->saveItem($request, $this->identity()->getUserId());
        
        $data['id'] = $id ? $id : $number;
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 删除数据（一条）
     *
     * @param $id 必选            
     */
    public function banItem(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $data['id'] = $id = $request->input('id');
        
        $demandService = new DemandService();
        $demandService->banItem($id);
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 修改状态（一条）
     *
     * @param $id 必选            
     */
    public function editItemStatus(ItemStatusRequest $request)
    {
        $data['id'] = $id = $request->input('id');
        $data['status'] = $status = $request->input('status');
        
        $demandService = new DemandService();
        $demandService->editItemStatus($id, $status);
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 刷新数据（一条）
     *
     * @param $id 必选            
     */
    public function refreshItem(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $data['id'] = $id = $request->input('id');
        
        $demandService = new DemandService();
        $demandService->refreshItem($id);
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 举报数据（一条）
     *
     * @param $id 必选            
     */
    public function reportItem(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $data['id'] = $id = $request->input('id');
        
        $demandService = new DemandService();
        $demandService->reportItem($id, $this->identity()->getUserId());
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 收藏数据（一条）
     *
     * @param $id 必选            
     * @param $type 必选            
     */
    public function collectionItem(ItemCollectionRequest $request)
    {
        $data['id'] = $id = $request->input('id');
        $data['type'] = $type = $request->input('type');
        
        $demandService = new DemandService();
        $demandService->collectionItem($id, $type, $this->identity()->getUserId());
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 批量删除我的收藏列表
     *
     * @param $ids 必选
     */
    public function deleteCollection(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required|array|between:1,50'
        ]);
        $data['ids'] = $ids = $request->input('ids');
        $userId = $this->identity()->getUserId();
    
        $demandService = new DemandService();
        $demandService->deleteCollection($ids, $userId);
    
        return $this->response->setResponseData($data)->getResponse();
    }
    
    /**
     * 我的收藏列表
     *
     * @param $page 可选            
     * @param $page_size 可选            
     */
    public function getCollectionList(Request $request)
    {
        $this->validate($request, [
            'page' => 'nullable|integer|between:1,10000',
            'page_size' => 'nullable|integer|between:1,100'
        ]);
        $page = intval($request->query('page', 1));
        $pageSize = intval($request->query('page_size', 50));
        $userId = $this->identity()->getUserId();
        
        $demandService = new DemandService();
        list ($collection, $count) = $demandService->selectCollectionList($page, $pageSize, $userId);
        
        $data['count'] = [
            'total' => $count,
            'page' => $page,
            'page_size' => $pageSize
        ];
        $data['data'] = new DemandListResource($collection);
        
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 拨打电话（一次）
     *
     * @param $id 必选            
     */
    public function dialItem(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $data['id'] = $id = $request->input('id');
        
        DemandCountVisitModel::incDial($id);
        
        return $this->response->setResponseData($data)->getResponse();
    }
}
